package com.tsmti.system.service.impl;

import com.google.common.collect.Lists;
import com.tsmti.core.common.constant.RedisConstants;
import com.tsmti.core.common.service.impl.BaseServiceImpl;
import com.tsmti.core.util.ConvertUtil;
import com.tsmti.core.util.RedisUtils;
import com.tsmti.core.util.StringUtils;
import com.tsmti.system.entity.DataDictionary;
import com.tsmti.system.entity.DataDictionaryGroup;
import com.tsmti.system.service.DataDictionaryGroupService;
import com.tsmti.system.service.DataDictionaryService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Package：com.tsmti.system.service.impl
 * @Class：DataDictionaryServiceImpl
 * @Description： 字典service
 * @Author：zcw
 * @Date：Created in 2018/5/16 16:11
 * @Company:
 * @Version：
 * @Modified By:
 */
@Transactional(rollbackFor = Exception.class)
@Service("dataDictionaryService")
public class DataDictionaryServiceImpl extends BaseServiceImpl<DataDictionary> implements DataDictionaryService{
    @Autowired
    private DataDictionaryGroupService dataDictionaryGroupService;
    /**
     * 保存字典
     * @param dictionary
     * @return
     */
    @Override
    public DataDictionary save(DataDictionary dictionary){
        dictionary = super.save(dictionary);
        updateRedis(dictionary);
        return dictionary;
    }

    /**
     * 更新字典
     * @param dictionary
     */
    @Override
    public void update(DataDictionary dictionary){
        dictionary = super.save(dictionary);
        updateRedis(dictionary);
    }

    @Override
    public void removeById(Serializable id) {
        DataDictionary dataDictionary = get(id);
        super.removeById(id);
        updateRedis(null);
    }

    /**
     * 批量删除字典
     * @param ids
     */
    @Override
    public void removeAllById(List<?> ids){
        for (Object id : ids) {
            super.removeById((Serializable) id);
        }
        updateRedis(null);
    }

    private void updateRedis(DataDictionary dictionary){
        Map<String, List<DataDictionary>> dataDictionaryMap = new HashMap<String, List<DataDictionary>>(16);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
        if(dictionary == null){
            //批量更新
            List<DataDictionary> dictionaryList = listByOrder();
            for (DataDictionary dict : dictionaryList) {
                List<DataDictionary> dictList = null;
                if(dataDictionaryMap != null){
                    dictList = dataDictionaryMap.get(dict.getGroupCode());
                }
                if (dictList != null) {
                    dictList.add(dict);
                } else {
                    dataDictionaryMap.put(dict.getGroupCode(), Lists.newArrayList(dict));
                }
            }
        }else {
            try {
                dataDictionaryMap = (Map<String, List<DataDictionary>>) RedisUtils.getObject(RedisConstants.DICTIONARY_CACHE);
                logger.info("读取数据字典缓存成功!");
            } catch (Exception e) {
                logger.warn("读取数据字典缓存失败!");
                e.printStackTrace();
            }
            DataDictionaryGroup dataDictionaryGroup = dataDictionaryGroupService.get(dictionary.getGroupId());
            if(dataDictionaryMap != null &&  dataDictionaryMap.size() >0){
                detachedCriteria.add(Restrictions.eq("groupId",dictionary.getGroupId()));
                detachedCriteria.add(Restrictions.eq("delFlag",0));
                List<DataDictionary> dictionaryList = list(detachedCriteria);
                dataDictionaryMap.put(dataDictionaryGroup.getCode(),dictionaryList);
            }
        }
        try {
            RedisUtils.setObject(RedisConstants.DICTIONARY_CACHE,dataDictionaryMap);
        }catch (Exception e){
            logger.warn("更新机构缓存失败!",e);
        }
    }

    @Override
    public List<DataDictionary> listByOrder() {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DataDictionary.class);
        detachedCriteria.add(Restrictions.eq("delFlag",0));
        detachedCriteria.addOrder(Order.asc("groupId"));
        detachedCriteria.addOrder(Order.asc("sort"));
        detachedCriteria.addOrder(Order.asc("id"));
        return list(detachedCriteria);
    }
}
